package mju.cn.oneweek.Interceptor;

import mju.cn.oneweek.HelloWorld;
import mju.cn.oneweek.HelloWorldImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @program: java-ee_31
 * @description:
 * @author: HP
 * @time: 2020/9/18 19:25
 */
public class InterceptorJdkProxy implements InvocationHandler {
    private Object target;
    private String interceptorClass = null;

    public InterceptorJdkProxy(Object target,String interceptorClass){
        this.target = target;
        this.interceptorClass=interceptorClass;
    }
    public static Object bind(Object target,String interceptorClass){
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),
                new InterceptorJdkProxy(target,interceptorClass));//（new HelloWorldImpl(),"mju.cn.Interceptor.MyInterceptor"）
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (interceptorClass== null){
            return method.invoke(target,args);
        }
        Object result = null;
        Interceptor interceptor = (Interceptor)Class.forName(interceptorClass).newInstance();
        if (interceptor.before(proxy,target,method,args)){
            result = method.invoke(target,args);
            System.out.println("11111111111111"+interceptor.before(proxy,target,method,args));//flase
        }else {
            interceptor.around(proxy,target,method,args);
        }
        interceptor.after(proxy,target,method,args);
        return result;
    }

    public static void main(String[] args) {
        HelloWorld proxy =(HelloWorld) InterceptorJdkProxy.bind(new HelloWorldImpl(),"mju.cn.Interceptor.MyInterceptor");
        proxy.sayHelloWorld();
    }
}
